package com.example.makerspace.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.cloudauth20221125.Client;
import com.aliyun.cloudauth20221125.models.EntElementVerifyRequest;
import com.aliyun.cloudauth20221125.models.EntElementVerifyResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.makerspace.config.AuthenticationConfig;
import com.example.makerspace.config.EnterpriseCertificationConfig;
import com.example.makerspace.config.SendMessageConfig;
import com.example.makerspace.dao.*;
import com.example.makerspace.domain.*;
import com.example.makerspace.dto.*;
import com.example.makerspace.enums.ResultCodeEnum;
import com.example.makerspace.manager.ApplicationManager;
import com.example.makerspace.manager.ApplicationV2Manager;
import com.example.makerspace.manager.CompetitionManager;
import com.example.makerspace.service.ApplicationService;
import com.example.makerspace.utils.*;
import com.example.makerspace.vo.BasicDataVO;
import com.example.makerspace.vo.CoreDataVO;
import com.example.makerspace.vo.UserInformationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author River
 * @version 1.0
 * @date 2023/9/27 21:52
 * @description:
 */

@Service
public class ApplicationServiceImpl implements ApplicationService {
    private final static String RESOURCE_PATH_PREFIX = "resource/";

  private  final  static  String   testHttpPrefix="https://119.45.199.13:3035/static/";
   private  final  static  String  devHttpPrefix="https://nism.ytcata.com:443/static/";

    private  final  static  String UserType="个人认证";

    private  final  static  String EntType="企业认证";

    private  final  static  Integer UserPoint=10;

    private  final  static  Integer EntPoint=10;
    @Resource
    private ApplicationManager applicationManager;


    @Resource
    private  StageFormDAO stageFormDAO;


    @Resource
    private  SmsErrLogDAO smsErrLogDAO;

    @Resource
    private  AgenciesDAO agenciesDAO;

    @Resource
    private  AgencyProductRelationshipsDAO agencyProductRelationshipsDAO;
    @Resource
    private ApplicationV2Manager applicationV2Manager;

    @Resource
    private  EntErrLogDAO entErrLogDAO;

    @Resource
    private CompetitionManager competitionManager;

    @Resource
    private AuthenticationConfig authenticationConfig;


    @Resource
    private  IntegralTasksDAO  integralTasksDAO;

    @Resource
    private  TaskTagDAO taskTagDAO;

    @Resource
    private  TaskFinishDAO taskFinishDAO;


    @Resource
    private UserAuthenticationDAO userAuthenticationDAO;

    @Resource
    private  PointBreakdownDAO pointBreakdownDAO;

    @Resource
    private UserDAO userDAO;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private ApplicationV2DAO applicationV2DAO;

    @Resource
    private EnterpriseCertificationConfig enterpriseCertificationConfig;

    @Resource
    private SendMessageConfig sendMessageConfig;

    @Resource
    private CompetitionSubmissionDAO competitionSubmissionDAO;

    @Resource
    private EnterpriseCertificationDAO enterpriseCertificationDAO;

    @Resource
    private  UserCompetitionRelationShipDAO userCompetitionRelationShipDAO;

    @Resource
    private  CompetitionDAO competitionDAO;

    @Resource
    private  MessageDAO messageDAO;

    @Resource
    private  SingInRecordDAO singInRecordDAO;



    @Resource
    private  DemandDAO demandDAO;

    @Override
    public Result addApplication(ApplicationDTO applicationDTO) {
        return applicationManager.addApplication(applicationDTO);
    }

    @Override
    public Result addApplication(ApplicationV2DTO applicationV2DTO) {
        return applicationV2Manager.addApplicationV2(applicationV2DTO);
    }


    @Override
    public Result checkApplication(HttpServletRequest request) {
        return applicationManager.checkApplication(request);
    }

    @Override
    public Result checkApplicationV2(HttpServletRequest request, Integer competitionParentId) {
        return applicationV2Manager.checkApplication(request, competitionParentId);
    }
    @Override
    public Result checkCompetition(PageRequest pageRequest) {
        return applicationV2Manager.checkCompetition(pageRequest);
    }

    @Override
    public Result selectCompetition(HttpServletRequest request, Integer competitionId,Integer competitionParentId) {
        return applicationV2Manager.selectCompetition(request, competitionId,competitionParentId);
    }


    @Override
    public Result processStatus(HttpServletRequest request, Integer competitionParentId) {
        return applicationV2Manager.processStatus(request,competitionParentId);
    }

    @Override
    public Result questionsRegistration(ApplicationV2DTO applicationV2DTO) {
        return applicationV2Manager.questionsRegistration(applicationV2DTO);
    }

    @Override
    public Result questionSubmit(CompetitionSubmissionDTO competitionSubmissionDTO) {
        return applicationV2Manager.questionSubmit(competitionSubmissionDTO);
    }
    @Override
    public Result updateCompetition(UserCompetitionRelationShipDTO userCompetitionRelationShipDTO) {
        return applicationV2Manager.updateCompetition(userCompetitionRelationShipDTO);
    }

    @Override
    public Result updateApplication(ApplicationDTO applicationDTO) {
        applicationDTO.setStatus(null);
        return applicationManager.updateApplication(applicationDTO);
    }

    @Override
    public Result updateApplication(Map<String, Object> params) {
        params.remove("status");
        return applicationV2Manager.update(params);
    }

    @Override
    public Result save(ApplicationDTO applicationDTO) {

        return applicationManager.save(applicationDTO);
    }

    @Override
    public Result save(ApplicationV2DTO applicationV2DTO) {
        return applicationV2Manager.save(applicationV2DTO);
    }

    @Override
    public Result submit(ApplicationDTO applicationDTO) {

        return applicationManager.submit(applicationDTO);
    }

    @Override
    public Result submit(ApplicationV2DTO applicationV2DTO) {
        return applicationV2Manager.submit(applicationV2DTO);
    }

    @Override
    public PageResult competitions(PageRequest pageRequest) {
        return competitionManager.presentCompetition(pageRequest);
    }

    @Override
    public Result competitionDetail(Map<String, Object> params) {
        return competitionManager.detail(params);
    }


    @Override
    public Result listApplication(PageRequest pageRequest) {
        return applicationV2Manager.listApplication(pageRequest);
    }

    @Override
    public Result vagueQuery(PageRequest pageRequest) {
        return applicationV2Manager.vagueQuery(pageRequest);
    }

    @Override
    public Result authentication(UserAuthenticationDTO userAuthenticationDTO) {
        MessageDO messageDO = new MessageDO();
        messageDO.setTitle("个人认证消息");
        messageDO.setType(1);
        messageDO.setUsername(userAuthenticationDTO.getPhone());

        String status = "";
        String msg = "";
        UserAuthenticationDO userAuthenticationDO = new UserAuthenticationDO();
        BeanUtils.copyProperties(userAuthenticationDTO, userAuthenticationDO);
        if(!ObjectUtils.isEmpty(userAuthenticationDTO.getBackground())){
            String background = FileUtils.saveMultipartFile2(userAuthenticationDTO.getBackground(), devHttpPrefix + RESOURCE_PATH_PREFIX + userAuthenticationDTO.getName(),
                    FileUtils.staticPath+RESOURCE_PATH_PREFIX+userAuthenticationDTO.getName());
            userAuthenticationDO.setBackground(background);
        }

        try {
            String host = authenticationConfig.getHost();
            String path = authenticationConfig.getPath();
            String appcode = authenticationConfig.getAppcode();
            String urlSend = host + path + "?idCard=" + userAuthenticationDTO.getIdCard() + "&name=" + URLEncoder.encode(userAuthenticationDTO.getName(), "UTF-8");// 【5】拼接请求链接
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                JSONObject jsonObject = JSONObject.parseObject(json);
                // 获取到key为shoppingCartItemList的值
                status = jsonObject.getString("status");
                msg = jsonObject.getString("msg");
                if (status.equals("01")) {
                    userAuthenticationDAO.insert(userAuthenticationDO);
                    UserDO userDO = userDAO.selectByPhone(userAuthenticationDO.getPhone());
                    List<ApplicationV2DO> applicationV2DOList = applicationV2DAO.selectAllByUsername(userAuthenticationDO.getPhone());

                    if (userDO != null) {
                        userDO.setIsAuthentication(1);
                        userDO.setAuthenticationType("个人认证");
                        userDO.setIndividual(userAuthenticationDTO.getName());
                        userDO.setIsUserAuthentication(1);

                        if(userDO.getMapAddress()==null) {
                            userDO.setMapAddress(userAuthenticationDTO.getMapAddress());
                        }
                        userDO.setEmail(userAuthenticationDTO.getEmail());

                        if(!ObjectUtils.isEmpty(userAuthenticationDTO.getAvatar())) {
                            String avatar = FileUtils.saveMultipartFile2(userAuthenticationDTO.getAvatar(), devHttpPrefix + RESOURCE_PATH_PREFIX + userAuthenticationDTO.getId(),
                                    FileUtils.staticPath + RESOURCE_PATH_PREFIX + userAuthenticationDTO.getId());
                            userDO.setHeadshot(avatar);
                        }
                        userDO.setPoints(userDO.getPoints()+UserPoint);
                        userDAO.updateById(userDO);
                    }
                    if (!CollectionUtils.isEmpty(applicationV2DOList)) {
                      for(ApplicationV2DO applicationV2DO:applicationV2DOList){
                          applicationV2DO.setIsAuthentication(1);
                          applicationV2DO.setAuthenticationType("个人认证");
                          applicationV2DAO.updateById(applicationV2DO);
                      }
                    }
                    PointBreakdownDO pointBreakdownDO = new PointBreakdownDO();
                    pointBreakdownDO.setType(UserType);
                    pointBreakdownDO.setUsername(userAuthenticationDTO.getPhone());
                    pointBreakdownDO.setDetails("个人认证,获得"+UserPoint+"积分");
                    pointBreakdownDO.setPoint("+"+UserPoint);
                    pointBreakdownDAO.insert(pointBreakdownDO);
                    TaskTagDO taskTagDO=taskTagDAO.selectByUserTaskName();
                    TaskFinishDO taskFinishDO = taskFinishDAO.selecByTaskAndUser(taskTagDO.getId(), userAuthenticationDTO.getPhone());
                    if(taskFinishDO!=null){
                        taskFinishDO.setIsFinish(1);
                        taskFinishDAO.updateById(taskFinishDO);
                    }
                    messageDO.setContent(userAuthenticationDTO.getName()+"您好!你的个人认证已经通过");
                    messageDAO.insert(messageDO);
                    try{
                        MessageUtils.sendMessage(userAuthenticationDTO.getPhone(), sendMessageConfig.getPersonalCertificationSuccess());
                    }catch (Exception e){
                        SmsErrLogDO smsErrLogDO = new SmsErrLogDO();
                        smsErrLogDO.setPhone(userAuthenticationDTO.getPhone());
                        smsErrLogDO.setType("个人认证");
                        smsErrLogDAO.insert(smsErrLogDO);
                    }


                }else {
                    messageDO.setContent(userAuthenticationDTO.getName()+"您好!你的个人认证失败");
                    messageDAO.insert(messageDO);
                    try{
                        MessageUtils.sendMessage(userAuthenticationDTO.getPhone(), sendMessageConfig.getPersonalCertificationFailed());
                    }catch (Exception e){
                        SmsErrLogDO smsErrLogDO = new SmsErrLogDO();
                        smsErrLogDO.setPhone(userAuthenticationDTO.getPhone());
                        smsErrLogDO.setType("个人认证");
                        smsErrLogDAO.insert(smsErrLogDO);
                    }

                }
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    return Result.error(ResultCodeEnum.App_Code);
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    return Result.error(ResultCodeEnum.Invalid_Url);
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    return Result.error(ResultCodeEnum.Invalid_Param_Location);
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    return Result.error(ResultCodeEnum.Unauthorized);
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    return Result.error(ResultCodeEnum.Quota_Exhausted);
                } else if (httpCode == 403 && error.equals("Api Market Subscription quota exhausted")) {
                    return Result.error(ResultCodeEnum.Quota_Exhausted);
                } else {
                    return Result.error(ResultCodeEnum.Other_Error);
                }
            }
        } catch (MalformedURLException e) {
            return Result.error(ResultCodeEnum.URL_Format);
        } catch (UnknownHostException e) {
            return Result.error(ResultCodeEnum.URL_Address);
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            e.printStackTrace();
        }
        if (status.equals("01")) {
            return Result.success(msg);
        }
        return Result.error(ResultCodeEnum.Other_Error, msg);
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    public Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(enterpriseCertificationConfig.getAccessKeyId())
                .setAccessKeySecret(enterpriseCertificationConfig.getAccessKeySecret())
                .setSignatureVersion("2019-06-01");
        config.endpoint = enterpriseCertificationConfig.getEndpoint();
        return new Client(config);
    }

    @Override
    public Result certification(EnterpriseCertificationDTO enterpriseCertificationDTO) {
        MessageDO messageDO = new MessageDO();
        messageDO.setTitle("企业认证消息");
        messageDO.setType(1);
        messageDO.setUsername(enterpriseCertificationDTO.getPhoneNumber());
        ArrayList<String> posters = new ArrayList<>();
        Client client = null;
        EnterpriseCertificationDO enterpriseCertificationDO = new EnterpriseCertificationDO();
        BeanUtils.copyProperties(enterpriseCertificationDTO, enterpriseCertificationDO);

        if(!ObjectUtils.isEmpty(enterpriseCertificationDTO.getLogo())){
            String logo = FileUtils.saveMultipartFile2(enterpriseCertificationDTO.getLogo(), devHttpPrefix+ RESOURCE_PATH_PREFIX + enterpriseCertificationDTO.getEntName(),
                    devHttpPrefix+RESOURCE_PATH_PREFIX+enterpriseCertificationDTO.getEntName());
            enterpriseCertificationDO.setLogo(logo);
        }else {
            enterpriseCertificationDO.setLogo("https://nism.ytcata.com/static/resource/2313/adf2c538802bee9458509e0dea614f7.jpg");
        }
        if(!ObjectUtils.isEmpty(enterpriseCertificationDTO.getPosters())){
            for(int  i=0;i<enterpriseCertificationDTO.getPosters().size();i++){
            {
                String fileName=ValidateCodeUtils.generateCode(4);
                String imagePath = FileUtils.saveMultipartFile2(enterpriseCertificationDTO.getPosters().get(i), devHttpPrefix + RESOURCE_PATH_PREFIX + fileName,
                        FileUtils.staticPath+RESOURCE_PATH_PREFIX+fileName);
                posters.add(imagePath);
            }
        }
        enterpriseCertificationDO.setPosters(posters);
        }else {
            String poster="https://nism.ytcata.com/static/resource/3KKb/91f79f13b90165194f338ee291f8471.jpg";
            posters.add(poster);
            enterpriseCertificationDO.setPosters(posters);
        }
        if(!ObjectUtils.isEmpty(enterpriseCertificationDTO.getLicense())) {
            String fileName=ValidateCodeUtils.generateCode(4);
            String licence = FileUtils.saveMultipartFile2(enterpriseCertificationDTO.getLicense(), devHttpPrefix + RESOURCE_PATH_PREFIX + fileName,
                    FileUtils.staticPath + RESOURCE_PATH_PREFIX +fileName);
            enterpriseCertificationDO.setLicense(licence);
        }
        try {
            client = createClient();
            EntElementVerifyRequest entElementVerifyRequest = new EntElementVerifyRequest()
                    .setSceneCode(ValidateCodeUtils.generateCodeNumber(10))
                    .setMerchantBizId(ValidateCodeUtils.generateCode(20))
                    .setMerchantUserId(ValidateCodeUtils.generateCodeNumber(20))
                    .setUserAuthorization("1")
                    .setInfoVerifyType("ENT_4META")
                    .setLicenseNo(enterpriseCertificationDTO.getLicenseNo())
                    .setEntName(enterpriseCertificationDTO.getEntName())
                    .setLegalPersonName(enterpriseCertificationDTO.getLegalPersonName())
                    .setLegalPersonCertNo(enterpriseCertificationDTO.getLegalPersonCertNo());
            enterpriseCertificationDO.setSceneCode(entElementVerifyRequest.getSceneCode());
            enterpriseCertificationDO.setMerchantBizId(entElementVerifyRequest.getMerchantBizId());
            enterpriseCertificationDO.setMerchantUserId(entElementVerifyRequest.getMerchantUserId());
            enterpriseCertificationDO.setUserAuthorization("1");
            enterpriseCertificationDO.setInfoVerifyType("ENT_4META");
            enterpriseCertificationDO.setCertificationResults(1);
            RuntimeOptions runtime = new RuntimeOptions();
            EntElementVerifyResponse response = client.entElementVerifyWithOptions(entElementVerifyRequest, runtime);
            if (response.getBody().message.equals("success")) {
                String bizCode = response.getBody().getResult().getBizCode();
                if(bizCode.equals("1")){
                    PointBreakdownDO pointBreakdownDO = new PointBreakdownDO();
                    pointBreakdownDO.setType(EntType);
                    pointBreakdownDO.setUsername(enterpriseCertificationDTO.getPhoneNumber());
                    pointBreakdownDO.setDetails("企业认证,获得"+EntPoint+"积分");
                    pointBreakdownDO.setPoint("+"+EntPoint);
                    pointBreakdownDAO.insert(pointBreakdownDO);
                    TaskTagDO taskTagDO=taskTagDAO.selectByEntTaskName();
                    TaskFinishDO taskFinishDO = taskFinishDAO.selecByTaskAndUser(taskTagDO.getId(), enterpriseCertificationDTO.getPhoneNumber());
                    if(taskFinishDO!=null){
                        taskFinishDO.setIsFinish(1);
                        taskFinishDAO.updateById(taskFinishDO);
                    }
                    messageDO.setContent("您好!您的"+enterpriseCertificationDTO.getEntName()+"已经认证成功!");
                    messageDAO.insert(messageDO);
                    enterpriseCertificationDAO.insert(enterpriseCertificationDO);
                    UserDO userDO = userDAO.selectByPhone(enterpriseCertificationDO.getPhoneNumber());
                    List<ApplicationV2DO> applicationV2DOList= applicationV2DAO.selectByAllUsername(enterpriseCertificationDO.getPhoneNumber());
                    if(userDO!=null){
                        userDO.setIsAuthentication(1);
                        userDO.setAuthenticationType("企业认证");
                        userDO.setIsEnterpriseCertification(1);
                        userDO.setEntName(enterpriseCertificationDTO.getEntName());
                        userDO.setCertificationResults(1);
                        userDO.setMapAddress(enterpriseCertificationDO.getMapAddress());
                        userDO.setPoints(userDO.getPoints()+EntPoint);
                        userDAO.updateById(userDO);
                    }
                    if (!CollectionUtils.isEmpty(applicationV2DOList)) {
                        for(ApplicationV2DO applicationV2DO:applicationV2DOList){
                            applicationV2DO.setIsAuthentication(1);
                            applicationV2DO.setAuthenticationType("企业认证");
                            applicationV2DO.setEntName(enterpriseCertificationDTO.getEntName());
                            applicationV2DAO.updateById(applicationV2DO);
                        }
                    }
                    MessageUtils.sendMessage(enterpriseCertificationDTO.getPhoneNumber(),sendMessageConfig.getEnterpriseCertificationSuccess());
                    return Result.success(ResultCodeEnum.Company_SUCCESS);
                }else {
                    messageDO.setContent("您好!您的"+enterpriseCertificationDTO.getEntName()+"认证失败!");
                    messageDAO.insert(messageDO);
                    try {
                        MessageUtils.sendMessage(enterpriseCertificationDTO.getPhoneNumber(),sendMessageConfig.getEnterpriseCertificationFailed());
                    }catch (Exception e){
                        SmsErrLogDO smsErrLogDO = new SmsErrLogDO();
                        smsErrLogDO.setPhone(enterpriseCertificationDTO.getPhoneNumber());
                        smsErrLogDO.setType("第一种:企业认证");
                        smsErrLogDAO.insert(smsErrLogDO);
                    }

                }

                return Result.success(ResultCodeEnum.Company_Error);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            // 复制代码运行请自行打印 API 的返回值


        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return Result.error(ResultCodeEnum.Company_Error);
    }
    public String phoneSecrecy(String phoneNum){
        if(phoneNum != null && phoneNum.length() > 4){
            if(phoneNum.length() == 11){
                phoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, phoneNum.length());
            }else{
                phoneNum = phoneNum.substring(0,phoneNum.length()-1) + "*";
            }
        }
        return phoneNum;
    }

    @Override
    public Result showUser(HttpServletRequest request) {
        UserInformationVO userInformationVO = new UserInformationVO();
        String username = JwtUtils.getUsername(request);
        String token = redisUtils.get(username);
        String header = request.getHeader("token");
        if(!token.equals(header)){
            return Result.error(ResultCodeEnum.UNSIGNED_USER);
        }
        UserDO userDO1 = userDAO.selectByUsername(username);
        userInformationVO.setIsProxy(0);
        List<StageFormDO> stageFormDOS = stageFormDAO.selectByUserName(username);
        if(CollectionUtils.isEmpty(stageFormDOS)){
            userInformationVO.setIsSubmit(0);
        }else {
            userInformationVO.setIsSubmit(1);
        }
        List<AgencyProductRelationshipsDO> agencyProductRelationshipsDOS = agencyProductRelationshipsDAO.selectByUserName(username);
        if(CollectionUtils.isEmpty(agencyProductRelationshipsDOS)){
            userInformationVO.setIsProxy(0);
        }else {
            for(AgencyProductRelationshipsDO agencyProductRelationshipsDO:agencyProductRelationshipsDOS){
                if(agencyProductRelationshipsDO.getState().equals("可代理")){
                    userInformationVO.setIsProxy(1);
                }
            }
        }
        if(userDO1!=null){
            if(userDO1.getRole().equals("super")||userDO1.getRole().equals("admin")||userDO1.getRole().equals("audit")){
                userInformationVO.setIsAdmin(1);
            }else {
                userInformationVO.setIsAdmin(0);
            }
        }
        if(userDO1!=null){
            userInformationVO.setIsExpert(userDO1.getIsExpert());
        }else {
            userInformationVO.setIsExpert(0);
        }
        if(username.equals("用户未登录")){
            return Result.error(ResultCodeEnum.UNSIGNED_USER);
        }
        List<UserDO> userDOS = userDAO.selectByAllUsername(username);
        userInformationVO.setUsername(phoneSecrecy(username));
        List<SingInRecordDO> singInRecordDOS = singInRecordDAO.selectByUserName(username);
        if(!CollectionUtils.isEmpty(singInRecordDOS)){
            userInformationVO.setIsSignIn(singInRecordDOS.get(0).getIsSign());
        }
        if(CollectionUtils.isEmpty(userDOS)){
            return  Result.error(ResultCodeEnum.Other_Error);
        }
        UserDO userDO = userDOS.get(0);

        userInformationVO.setId(userDO.getId());
        List<EnterpriseCertificationDO> enterpriseCertificationDOS = enterpriseCertificationDAO.selectByPhoneNumber(userDO.getUsername());
        userInformationVO.setAvatar(userDO.getAvatar());
        userInformationVO.setPoints(userDO.getPoints());
        userInformationVO.setMeetings(userDO.getMeetings());
        userInformationVO.setBackground(userDO.getBackground());
        userInformationVO.setNickname(userDO.getNickname());
        userInformationVO.setRole(userDO.getRole());
        userInformationVO.setMapAddress(userDO.getMapAddress());
        if(CollectionUtils.isEmpty(enterpriseCertificationDOS)){
            userInformationVO.setCertificationResults(null);
        }else {
            userInformationVO.setCertificationResults(enterpriseCertificationDOS.get(0).getCertificationResults());
        }
        if(userDO.getIsAuthentication()==1){
            userInformationVO.setIsAuthentication(1);
            if(userDO.getAuthenticationType().equals("个人认证")){
                userInformationVO.setAuthenticationType("个人认证");
                userInformationVO.setIsPersonalCertification(1);
                List<UserAuthenticationDO> userAuthenticationDOS = userAuthenticationDAO.selectByPhoneNumber(userDO.getUsername());
                List<EnterpriseCertificationDO> enterpriseCertificationDOS1 = enterpriseCertificationDAO.selectByPhoneNumber(userDO.getUsername());
                if(!CollectionUtils.isEmpty(enterpriseCertificationDOS1)&&enterpriseCertificationDOS1.get(0).getCertificationResults()==1){
                    userInformationVO.setIsEnterpriseCertification(1);
                }else {
                        userInformationVO.setIsEnterpriseCertification(0);
                }
                if(!CollectionUtils.isEmpty(userAuthenticationDOS)){
                    CopyIndividual(userAuthenticationDOS.get(0), userInformationVO);
                    userInformationVO.setIndividualName(userAuthenticationDOS.get(0).getName());
                    if(userDO.getIndustry()!=null){
                        userInformationVO.setIndustry(userDO.getIndustry());
                    }
                    if(userDO.getEmail()!=null){
                        userInformationVO.setEmail(userDO.getEmail());
                    }
                }

            }else {
                userInformationVO.setAuthenticationType("企业认证");
                userInformationVO.setIsEnterpriseCertification(1);
                List<UserAuthenticationDO> userAuthenticationDOS = userAuthenticationDAO.selectByPhoneNumber(userDO.getUsername());
                if(!CollectionUtils.isEmpty(userAuthenticationDOS)){
                    userInformationVO.setIsPersonalCertification(1);
                }else {
                    userInformationVO.setIsPersonalCertification(0);
                }
                if(!CollectionUtils.isEmpty(enterpriseCertificationDOS)){
                    BeanUtils.copyProperties(enterpriseCertificationDOS.get(0),userInformationVO);
                    if(userDO.getEmail()!=null){
                        userInformationVO.setEmail(userDO.getEmail());
                    }
                }
                List<DemandDO> demandDOS = demandDAO.selectByUserName(username);
                List<UserCompetitionRelationShipDO> userCompetitionRelationShipDOS = userCompetitionRelationShipDAO.selectByUsername(username);
                userInformationVO.setDemandDO(demandDOS);
                userInformationVO.setUserCompetitionRelationShipDOS(userCompetitionRelationShipDOS);

            }
        }else {
            userInformationVO.setIsAuthentication(0);
            userInformationVO.setIsPersonalCertification(userDO.getIsUserAuthentication());
            userInformationVO.setIsEnterpriseCertification(0);
            BeanUtils.copyProperties(userDO,userInformationVO,"username");
        }

        return Result.success(userInformationVO);
    }

    public    UserInformationVO CopyIndividual(UserAuthenticationDO userAuthenticationDO,UserInformationVO userInformationVO){
        if(userAuthenticationDO.getBackground()==null){
            BeanUtils.copyProperties(userAuthenticationDO,userInformationVO,"background");
            return  userInformationVO;
        }else {
            BeanUtils.copyProperties(userAuthenticationDO,userInformationVO);
            return  userInformationVO;
        }
    }
    @Override
    public Result updateUser(UserInfoDTO userInfoDTO) {
        return  applicationV2Manager.updateUser(userInfoDTO);
    }

    @Override
    public Result checkQuestions(ApplicationV2DTO applicationV2DTO) {
        return  applicationV2Manager.checkQuestions(applicationV2DTO);
    }

    @Override
    public Result showAllQuestionSubmit(String username,Integer competitionId) {
        List<CompetitionSubmissionDO> competitionSubmissionDOS = competitionSubmissionDAO.selectByUsernameAndId(username,competitionId);
        return Result.success(competitionSubmissionDOS);
    }

    @Override
    public Result showProducts(PageRequest pageRequest) {
        return applicationV2Manager.showProducts(pageRequest);
    }

    @Override
    public Result addProducts(DemandDTO demandDTO) {
        return  applicationV2Manager.addProducts(demandDTO);
    }

    @Override
    public Result updateProducts(DemandDTO demandDTO) {
        return  applicationV2Manager.updateProducts(demandDTO);
    }

    @Override
    public Result deleteProducts(Integer id) {
        return applicationV2Manager.deleteProducts(id);
    }

    @Override
    public Result uploadCertification(EnterpriseCertificationDTO enterpriseCertificationDTO) {
        return applicationV2Manager.uploadCertification(enterpriseCertificationDTO);
    }

    @Override
    public Result listCertification() {
        return applicationV2Manager.listCertification();
    }

    @Override
    public Result updateCertification(EnterpriseCertificationDTO enterpriseCertificationDTO) {
        return applicationV2Manager.updateCertification(enterpriseCertificationDTO);
    }

    @Override
    public Result detailProduct(Integer id, Integer type) {
        return applicationV2Manager.detailProduct(id,type);
    }





    @Override
    public Result addUserProducts(DemandDTO demandDTO) {
        return applicationV2Manager.addUserProducts(demandDTO);
    }

    @Override
    public Result showUserProducts(PageRequest pageRequest) {
        return applicationV2Manager.showUserProducts(pageRequest);
    }

    @Override
    public Result updateQuestionSubmit(CompetitionSubmissionDTO competitionSubmissionDTO) {
        return applicationV2Manager.updateQuestionSubmit(competitionSubmissionDTO);
    }

    @Override
    public Result showCompetitionState(HttpServletRequest request) {
        return applicationV2Manager.showCompetitionState(request);
    }

    @Override
    public Result showUserCompetition(HttpServletRequest request, Integer competitionId) {
        return applicationV2Manager.showUserCompetition(request,competitionId);
    }

    @Override
    public Result updateAvatar(UserDTO userDTO) {
        return applicationV2Manager.updateAvatar(userDTO);
    }

    @Override
    public Result addPraise(DemandDTO demandDTO) {
        return applicationV2Manager.addPraise(demandDTO);
    }

    @Override
    public Result addCollection(DemandDTO demandDTO) {
        return applicationV2Manager.addCollection(demandDTO);
    }

    @Override
    public Result showOtherProduct(Integer id, String username) {
        return  applicationV2Manager.showOtherProduct(id,username);
    }

    @Override
    public Result showPraise(String username) {
        return  applicationV2Manager.showPraise(username);
    }

    @Override
    public Result showCollection(String username) {
        return  applicationV2Manager.showCollection(username);
    }

    @Override
    public Result replacementCertification(Integer id, String username) {
        return  applicationV2Manager.replacementCertification(id,username);
    }

    @Override
    public Result AllDeleteRecord() {
        return  applicationV2Manager.AllDeleteRecord();
    }

    @Override
    public Result detailProductAndShow(Integer id) {
        return  applicationV2Manager.detailProductAndShow(id);
    }

    @Override
    public Result showAllPraiseUnRead(String username) {
        return  applicationV2Manager.showAllPraiseUnRead(username);
    }

    @Override
    public Result userEnroll() {
        return  applicationV2Manager.userEnroll();
    }

    @Override
    public Result authenticationData() {
        return  applicationV2Manager.authenticationData();
    }

    @Override
    public Result questionsRegistrationData() {
     return  applicationV2Manager.questionsRegistrationData();
    }

    @Override
    public Result openMarketData() {
        return  applicationV2Manager.openMarketData();
    }

    @Override
    public Result productData() {
        return  applicationV2Manager.productData();
    }

    @Override
    public Result userEnrollAllData() {
        return  applicationV2Manager.userEnrollAllData();
    }

    @Override
    public Result enterpriseAllData() {
        return  applicationV2Manager.enterpriseAllData();
    }

    @Override
    public Result individualAllDate() {
        return  applicationV2Manager.individualAllDate();
    }

    @Override
    public Result openMarketAllData() {
        return  applicationV2Manager.openMarketAllData();
    }

    @Override
    public Result competitionAllDate() {
        return  applicationV2Manager.competitionAllDate();
    }

    @Override
    public Result webClicks() {
        return  applicationV2Manager.webClicks();
    }

    @Override
    public Result addWebClicks() {
        return  applicationV2Manager.addWebClicks();
    }

    @Override
    public Result showEnterprise(HttpServletRequest request) {
        return  applicationV2Manager.showEnterprise(request);
    }

    @Override
    public Result addBulletins(ProductBulletinsDTO bulletinsDTO) {
        return  applicationV2Manager.addBulletins(bulletinsDTO);
    }

    @Override
    public Result updateBulletins(ProductBulletinsDTO bulletinsDTO) {
        return  applicationV2Manager.updateBulletins(bulletinsDTO);
    }

    @Override
    public Result deleteBulletins(Integer id) {
        return  applicationV2Manager.deleteBulletins(id);
    }

    @Override
    public Result selectAllProductsBulletins(PageRequest pageRequest) {
        return  applicationV2Manager.selectAllProductsBulletins(pageRequest);
    }

    @Override
    public Result selectProductsBulletins() {
        return  applicationV2Manager.selectProductsBulletins();
    }

    @Override
    public Result artificialIntelligence() {
        return  applicationV2Manager.artificialIntelligence();
    }



    @Override
    public Result smsRegistration() {
        return  applicationV2Manager.smsRegistration();
    }

    @Override
    public Result deleteProductPicture(DeleteProductsDTO deleteProductsDTO) {
        return  applicationV2Manager.deleteProductPicture(deleteProductsDTO);
    }

    @Override
    public Result awaitReviewed() {
        return  applicationV2Manager.awaitReviewed();
    }

    @Override
    public Result authenticationReviewed() {
        return  applicationV2Manager.authenticationReviewed();
    }

    @Override
    public Result userAreaMapData() {
        return  applicationV2Manager.userAreaMapData();
    }

    @Override
    public Result awaitReviewedDate() {
        return  applicationV2Manager.awaitReviewedDate();
    }

    @Override
    public Result authenticationReviewedDate() {
        return  applicationV2Manager.authenticationReviewedDate();
    }

    @Override
    public Result addShare(DemandDTO demandDTO) {
        return  applicationV2Manager.addShare(demandDTO);
    }

    @Override
    public Result test() {
        return  applicationV2Manager.test();
    }

    @Override
    public Result getBooks(HttpServletRequest request) {
        return  applicationV2Manager.getBooks(request);
    }

    @Override
    public Result userAreaMapData1() {
        return  applicationV2Manager.userAreaMapData1();
    }
    @Override
    public Result userEnrollDetailData() {
        return  applicationV2Manager.userEnrollDetailData();
    }

    @Override
    public Result entDetail() {
        return  applicationV2Manager.entDetail();
    }

    @Override
    public Result individualDetail() {
        return  applicationV2Manager.individualDetail();
    }

    @Override
    public Result questionsDetail() {
        return  applicationV2Manager.questionsDetail();
    }

    @Override
    public Result ProductDetail() {
        return  applicationV2Manager.ProductDetail();
    }

    @Override
    public Result smsDetail() {
        return  applicationV2Manager.smsDetail();
    }

    @Override
    public Result productDetailByProvince(String province) {
        return  applicationV2Manager.productDetailByProvince(province);
    }

    @Override
    public Result productDetailShow() {
        return  applicationV2Manager.productDetailShow();
    }

    @Override
    public CoreDataVO coreData() {
        return  applicationV2Manager.coreData();
    }

    @Override
    public CoreDataVO dataOverview() {
        return  applicationV2Manager.dataOverview();
    }

    @Override
    public CoreDataVO realNamePendingReview() {
        return  applicationV2Manager.realNamePendingReview();
    }

    @Override
    public CoreDataVO productMap() {
        return  applicationV2Manager.productMap();
    }

    @Override
    public CoreDataVO showProduct() {
        return  applicationV2Manager.showProduct();
    }

    @Override
    public CoreDataVO userChanges() {
        return  applicationV2Manager.userChanges();
    }

    @Override
    public CoreDataVO productSort() {
        return  applicationV2Manager.productSort();
    }

    @Override
    public CoreDataVO productToReviewed() {
        return  applicationV2Manager.productToReviewed();
    }

    @Override
    public Result searchEnterprise(String entName) {
        return  applicationV2Manager.searchEnterprise(entName);
    }

    @Override
    public BasicDataVO roseChart() {
        return  applicationV2Manager.roseChart();
    }

    @Override
    public BasicDataVO roseChart1() {
        return  applicationV2Manager.roseChart1();
    }

    @Override
    public BasicDataVO basicInformation() {
        return  applicationV2Manager.basicInformation();
    }

    @Override
    public BasicDataVO productSortV() {
        return  applicationV2Manager.productSortV();
    }

    @Override
    public BasicDataVO callDay() {
        return  applicationV2Manager.callDay();
    }

    @Override
    public BasicDataVO questionsData() {
        return  applicationV2Manager.questionsData();
    }

    @Override
    public BasicDataVO questionsRadar() {
        return  applicationV2Manager.questionsRadar();
    }

    @Override
    public BasicDataVO productComparison() {
        return  applicationV2Manager.productComparison();
    }

    @Override
    public BasicDataVO customerNumber() {
        return  applicationV2Manager.customerNumber();
    }

    @Override
    public BasicDataVO regionalReleases() {
        return  applicationV2Manager.regionalReleases();
    }

    @Override
    public BasicDataVO radar() {
        return  applicationV2Manager.radar();
    }

    @Override
    public Result uploadDocument(StageFormDTO stageFormDTO) {
        return  applicationV2Manager.uploadDocument(stageFormDTO);
    }

    @Override
    public BasicDataVO userSign() {
        return  applicationV2Manager.userSign();
    }

    @Override
    public BasicDataVO pointSort() {
        return  applicationV2Manager.pointSort();
    }

    @Override
    public Result showTable(HttpServletRequest request) {
        return  applicationV2Manager.showTable(request);
    }


}

